//
//  SMSInfoVC.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/4/21.
//  Copyright © 2019 NJMifi. All rights reserved.
//

import UIKit

class SMSInfoVC: RootVC {
    
    private var data : [[SMSListModel.Message]] = []
    
    private lazy var editView: EditView = {
        let view = EditView()
        view.cancelHandle = ({ [weak self] in
            self!.cancelEdit()
        })
        view.deleteHandle = ({ [weak self] in
            self!.deleteAction()
        })
        return view
    }()
    
    private lazy var tableView: UITableView = {
        let tab = UITableView(frame: CGRect(x: 0, y: naviView!.bottom, width: screenWidth, height: screenHeight - naviView!.bottom), style: .grouped)
        tab.backgroundColor = clearColor
        tab.rowHeight = 80
        tab.register(SMSInfoListCell.self, forCellReuseIdentifier: "cell")
        tab.delegate = self
        tab.dataSource = self
        tab.separatorStyle = .none
        
   
        
        return tab
    }()
    
    
 
    
    override func configView() {
        configNaviView(title: "SMS")
        view.backgroundColor = colorRGBA(red: 245, green: 245, blue: 245, alpha: 1)
        view.addSubview(tableView)
        view.addSubview(editView)
        
        rightBtn?.backgroundColor = clearColor
        rightBtn?.setImage(UIImage(named: "sms_new"), for: .normal)
        rightBtn?.setTitleColor(whiteColor, for: .normal)
        rightBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        
    }
    
    override func rightBtnClicked(sender: UIButton) {
        let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let newAction = UIAlertAction(title: "New", style: .default) {[weak self] (action) in
            let newVC = SMSDetailVC()
            self?.navigationController?.pushViewController(newVC, animated: true)
        }
        let editAction = UIAlertAction(title: "Edit", style: .default) {[weak self](action) in
            sender.isHidden = true
            self!.tableView.allowsMultipleSelectionDuringEditing = true
            self!.tableView.setEditing(true, animated: true)
            self!.tableView.height = screenHeight - self!.naviView!.bottom - self!.editView.height
            self!.editView.show()
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alertVC.addAction(newAction)
        if data.count > 0 {
            alertVC.addAction(editAction)
        }
        alertVC.addAction(cancelAction)
        present(alertVC, animated: true, completion: nil)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        getData()
    }
    
    private func getData() {
        net_getSMSList {[weak self] (list) in
            if list != nil {
                self!.convertData(list: list!)
            }else{
                
                self?.data.removeAll()
                
            }
            self!.tableView.reloadData()
        }
    }
    
    private func convertData(list:[SMSListModel.Message]) {
        var arr : [[SMSListModel.Message]] = []
        var numbers : [String] = []
        for message in list {
            numbers.append(message.number!)
        }
        let _numbers = Array(Set(numbers)).sorted()
        for num in _numbers {
            arr.append(list.filter{$0.number! == num})
        }
        data = arr;
    }
    
    private func cancelEdit() {
        tableView.setEditing(false, animated: true)
        rightBtn!.isHidden = false
        tableView.height = screenHeight - naviView!.bottom
        editView.dismiss()
    }
    
    private func deleteAction() {
        let willDelete = tableView.indexPathsForSelectedRows

        if willDelete == nil {
            
            return
        }
        
        var msg_id:String = ""
        for index in willDelete! {
            let row = index.row

            for item in data[row] {
                
                msg_id =  msg_id + item.id! + ";"
                
            }
            
        }
        net_deleteSMS(id: msg_id) {[weak self] (success) in
            if success{
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
                      self!.getData()
                })
                
              
            }
        }
        
        
    }
}

extension SMSInfoVC : UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard !tableView.isEditing else {
            return
        }

        
        var msg_id:String = ""
        
        for item in data[indexPath.row] {
            
            msg_id =  msg_id + item.id! + ";"
            
        }
        
        
        net_setMessageReaded(msg_id: msg_id)
        let newVC = SMSDetailVC(phone: data[indexPath.row].first!.number,list:data[indexPath.row])
        navigationController?.pushViewController(newVC, animated: true)
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SMSInfoListCell
        cell.refresh(data:data[indexPath.row].last!)
        return cell;
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}

fileprivate class EditView : UIView {
    var cancelHandle : (()->())?
    var deleteHandle : (()->())?
    
    private lazy var cancelBtn : UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: screenWidth / 2, height: 60))
        btn.backgroundColor = themeColor
        btn.setTitle("  Cancel", for: .normal)
        btn.setTitleColor(whiteColor, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 23)
        btn.setImage(UIImage(named: "cancel"), for: .normal)
        btn.tag = 0
        btn.addTarget(self, action: #selector(btnAction(sender:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton(frame: CGRect(x: screenWidth / 2, y: 0, width: screenWidth / 2, height: 60))
        btn.backgroundColor = themeColor
        btn.setTitle("  Delete", for: .normal)
        btn.setTitleColor(whiteColor, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 23)
        btn.setImage(UIImage(named: "del_sms"), for: .normal)
        btn.tag = 1
        btn.addTarget(self, action: #selector(btnAction(sender:)), for: .touchUpInside)
        return btn
    }()
    
    init() {
        super.init(frame: .zero)
        configView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func configView() {
        frame = CGRect(x: 0, y: screenHeight, width: screenWidth, height: 10 + tabbarHeight)
        backgroundColor = themeColor
        addSubview(cancelBtn)
        addSubview(deleteBtn)
    }
    
    @objc private func btnAction(sender:UIButton) {
        if sender.tag == 0 {
            if cancelHandle != nil {
                cancelHandle!()
            }
        }else {
            if deleteHandle != nil {
                deleteHandle!()
            }
        }
    }
    
    func show() {
        UIView.animate(withDuration: 0.2) { [weak self] in
            self!.bottom = screenHeight
        }
    }
    
    func dismiss() {
        UIView.animate(withDuration: 0.2) { [weak self] in
            self!.top = screenHeight
        }
    }
    
}
